package net.dgg.iboss.sc.backservice.task.service;

import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.sc.backservice.task.dao.ProductOrderDao;
import net.dgg.iboss.sc.backservice.task.entity.ProductOrder;
import net.dgg.iboss.sc.backservice.task.entity.TimeoutPunishDto;
import net.dgg.iboss.sc.backservice.task.entity.UserEntity;
import net.dgg.iboss.sc.backservice.task.entity.credentail.CertificateMatchingEntity;
import net.dgg.iboss.sc.backservice.task.entity.credentail.CredentialInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CertificateOutTimeOrPunishService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CertificateMatchingService certificateMatchingService;
    @Autowired
    private CredentialInfoService credentialInfoService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private UserService userService;
    @Autowired
    private NodeTimeOutPunishService nodeTimeOutPunishService;
    @Autowired
    private ProductOrderDao productOrderDao;
    /**
     *超期提醒
     */
    public void outTimeAlert(){
        List<CredentialInfo> credentialInfoList = credentialInfoService.getCertificateMatchingList();
        if(credentialInfoList.size()>0){
            for(CredentialInfo credentialInfo : credentialInfoList){
                CertificateMatchingEntity certificateMatchingEntity = certificateMatchingService.getMatchingByMap(credentialInfo.getCertificateSpecialtyId(),credentialInfo.getCertificateTypeId(),credentialInfo.getCertificateLevel());
                if(null !=certificateMatchingEntity){
                    try{
                        Integer days = certificateMatchingEntity.getMatchingTime();
                        Integer isNatureOrWorkDay = certificateMatchingEntity.getIsNatureWorkDay();
                        Date currentDate = commonService.getDateFromStartByType(credentialInfo.getLastOutgoingTime(),
                                days,Long.valueOf(days)*24*3600,
                                isNatureOrWorkDay);
                        //超期推送消息
                        if(new Date().getTime()>currentDate.getTime()) {
                            List<UserEntity> users = new ArrayList<>();

                            //证书出库人
                            UserEntity outUser = userService.findUserById(credentialInfo.getOutgoingOperaterId());
                            if (outUser != null) {
                                users.add(outUser);
                            }
                            //证书预定人
                            UserEntity reserveUser = userService.findUserById(credentialInfo.getCertificateUserId());
                            if (reserveUser != null) {
                                users.add(reserveUser);
                            }
                            //出库天数
                            int outDay = DateUtil.daysBetween(credentialInfo.getLastOutgoingTime(), new Date());
                            //超期天数
                            int overDay =DateUtil.daysBetween(currentDate, new Date());
                            //您好，{持证人}的{证书名称}已出库x天，超期x天未匹配，请及跟踪时处理！
                            String msg[] = new String[]{credentialInfo.getPersonalName(), credentialInfo.getCertificateName(),String.valueOf(outDay),String.valueOf(overDay)};
                            commonService.sendMsg(users, msg, "ZZSC_ZS_MATCH_OUT");
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                        logger.error("证书匹配:"+credentialInfo.getCertificateName()+",匹配超期提醒消息发送失败！");
                    }
                }
            }

        }
    }

    /**
     * 匹配超期扣罚
     */
    public void outTimePunish(){
            try{
                List<CredentialInfo> credentialInfoList = credentialInfoService.getCertificateMatchingList();
                Map<String,Object> returnMap = new HashMap<String,Object>();
                List<TimeoutPunishDto> list = new ArrayList<>();
                List<Long> idList = new ArrayList<>();
                if(credentialInfoList.size()>0){
                    for(CredentialInfo credentialInfo : credentialInfoList){
                        ProductOrder order = productOrderDao.selectByPrimaryKey(credentialInfo.getScOrderId());
                        CertificateMatchingEntity certificateMatchingEntity = certificateMatchingService.getMatchingByMap(credentialInfo.getCertificateSpecialtyId(),credentialInfo.getCertificateTypeId(),credentialInfo.getCertificateLevel());
                        if(null !=certificateMatchingEntity && null != order && (null == order.getPunishStatus() || 0 == order.getPunishStatus())){
                            Integer days = certificateMatchingEntity.getMatchingTime();
                            Integer isNatureOrWorkDay = certificateMatchingEntity.getIsNatureWorkDay();
                            Date currentDate = commonService.getDateFromStartByType(credentialInfo.getLastOutgoingTime(),
                                    days,Long.valueOf(days)*24*3600,
                                    isNatureOrWorkDay);
                            //进行扣罚
                            if(new Date().getTime()>currentDate.getTime()) {
                                this.matchingPunish(order,credentialInfo,certificateMatchingEntity,currentDate);
                            }
                        }
                    }

                }

            }catch (Exception e){
                e.printStackTrace();
                logger.error("证书匹配超期扣罚失败！");
            }
    }






    @Transactional
    public void matchingPunish(ProductOrder order,CredentialInfo credentialInfo,CertificateMatchingEntity certificateMatchingEntity,Date currentDate){
        try {
            List<TimeoutPunishDto> list = new ArrayList<>();
            TimeoutPunishDto timeoutPunishDto = new TimeoutPunishDto();
            timeoutPunishDto.setBusinessCode(order.getBusinessTypeCode());
            timeoutPunishDto.setBusinessName(order.getBusinessTypeName());
            timeoutPunishDto.setFlowUserId(credentialInfo.getCertificateUserId());
            timeoutPunishDto.setFlowUserName(credentialInfo.getCertificateUserName());
            timeoutPunishDto.setProductOrgId(order.getProductOrgId());
            timeoutPunishDto.setProductOrgName(order.getProductOrgName());
            timeoutPunishDto.setOrgId(credentialInfo.getCertificateUserOrgId());
            timeoutPunishDto.setOrgName(credentialInfo.getCertificateUserOrgName());
            timeoutPunishDto.setOrderId(order.getOrderId());
            timeoutPunishDto.setOrderNo(order.getOrderNo());
            timeoutPunishDto.setProductOrderId(order.getId());
            timeoutPunishDto.setProductOrderNo(order.getScProductOrderNo());
            timeoutPunishDto.setCustomerId(order.getCustomerId());
            timeoutPunishDto.setCustomerName(order.getCustomerName());
            timeoutPunishDto.setCustomerNo(order.getCustomerNo());
            timeoutPunishDto.setCustomerPhone(order.getCustomerPhone());
            timeoutPunishDto.setNoCode("zspp");
            timeoutPunishDto.setNoName("证书匹配");
            timeoutPunishDto.setVersion("version1");
            timeoutPunishDto.setTimeOutTime(currentDate);
            timeoutPunishDto.setPunishTime(new Date());
            timeoutPunishDto.setUpdaterId(1l);
            timeoutPunishDto.setUpdaterName("定时器执行");
            timeoutPunishDto.setUpdaterOrgId(1l);
            timeoutPunishDto.setUpdateTime(new Date());
            timeoutPunishDto.setType(2);
            if (certificateMatchingEntity.getUnit()==2) {
                timeoutPunishDto.setPoints(new BigDecimal(certificateMatchingEntity.getPunishCount()));
                timeoutPunishDto.setMoney(new BigDecimal(0));
            }
            if (certificateMatchingEntity.getUnit()==1) {
                timeoutPunishDto.setMoney(new BigDecimal(certificateMatchingEntity.getPunishCount()));
                timeoutPunishDto.setPoints(new BigDecimal(0));
            }
            timeoutPunishDto.setCreateTime(new Date());
            Map param = new HashMap(1);
            param.put("timeoutPunishListDtos", list );
           Integer code = nodeTimeOutPunishService.matchingtPunish(param);
           if(code == 0){
               productOrderDao.updateMatchingStatus(order.getId());
               //推送消息
               //您好，{持证人}{证书名称}匹配超期，对您扣罚{扣罚数量}{扣罚单位}，请查看确认
               List<UserEntity> users = new ArrayList<>();
               //扣罚人
               UserEntity userEntity = userService.findUserById(credentialInfo.getCertificateUserId());
               users.add(userEntity);
               String unit = certificateMatchingEntity.getUnit() == 1 ? "金额" : "操行分";
               String msg[] = new String[]{credentialInfo.getPersonalName(),credentialInfo.getCertificateName(),certificateMatchingEntity.getPunishCount().toString(),unit};
               commonService.sendMsg(users, msg, "ZZSC_ZS_MATCH_PUNISH");
           }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("证书匹配超期扣罚失败！");
        }
    }
}
